package com.demo.service.impl;

import com.demo.dto.Result;
import com.demo.entity.UserCollect;
import com.demo.mapper.UserCollectMapper;
import com.demo.service.UserCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.UserHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class UserCollectServiceImpl extends ServiceImpl<UserCollectMapper, UserCollect> implements UserCollectService {

    UserCollect getUserCollect(Integer answerId, Integer userId) {
        return query().eq("user_id", userId)
                .eq("answer_id", answerId).one();
    }

    @Override
    public Result<UserCollect> collect(Integer answerId) {
        Integer userId = UserHolder.getUser().getUserId();
        UserCollect userCollect = getUserCollect(answerId, userId);
        // 判断是否已收藏
        if (userCollect != null) {
            // 已收藏，删除收藏记录
            removeById(userCollect.getCollectId());
            return Result.ok(userCollect, "取消收藏成功");
        }
        else {
            // 未收藏，新建收藏记录
            UserCollect userCollectInsert = new UserCollect(null, userId, answerId, null);
            try {
                save(userCollectInsert);
                return Result.ok(getById(userCollectInsert.getCollectId()), "收藏成功");
            }
            catch (Exception e) {
                return Result.fail("外键约束：用户id或回答id有误");
            }
        }

    }
}
